#!/usr/bin/env python3
"""
使用uv管理依赖的儿童肺炎治疗咨询专家智能体启动脚本
"""

import os
import sys
import subprocess
import shutil

def check_uv():
    """检查uv是否已安装"""
    if not shutil.which("uv"):
        print("❌ uv未安装")
        print("请安装uv：")
        print("  curl -LsSf https://astral.sh/uv/install.sh | sh")
        print("  # 或使用brew：")
        print("  brew install uv")
        return False
    return True

def setup_env():
    """设置uv虚拟环境和依赖"""
    print("🚀 使用uv设置虚拟环境...")
    
    # 检查是否已存在虚拟环境
    if not os.path.exists(".venv"):
        print("🔄 创建虚拟环境...")
        try:
            subprocess.run(["uv", "venv"], check=True)
            print("✅ 虚拟环境创建成功")
        except subprocess.CalledProcessError as e:
            print(f"❌ 创建虚拟环境失败: {e}")
            return False
    
    # 安装依赖
    print("📦 安装项目依赖...")
    try:
        subprocess.run(["uv", "pip", "install", "-e", "."], check=True)
        print("✅ 依赖安装完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ 依赖安装失败: {e}")
        return False

def check_env():
    """检查环境变量"""
    if not os.path.exists(".env"):
        print("⚠️  未找到.env文件，创建中...")
        with open(".env", "w") as f:
            f.write("KIMI_API_KEY=your_kimi_api_key_here\n")
            f.write("KIMI_BASE_URL=https://api.moonshot.cn/v1\n")
        print("📋 已创建.env文件，请配置KIMI_API_KEY")
        return False
    
    with open(".env", "r") as f:
        content = f.read()
        if "your_kimi_api_key_here" in content:
            print("⚠️  请先在.env文件中设置您的KIMI_API_KEY")
            return False
    
    return True

def activate_and_run():
    """激活虚拟环境并运行应用"""
    print("🎯 启动Streamlit应用...")
    
    # 设置环境变量
    env = os.environ.copy()
    
    # 根据操作系统设置虚拟环境激活
    if os.name == 'nt':  # Windows
        activate_script = os.path.join(".venv", "Scripts", "activate")
        streamlit_path = os.path.join(".venv", "Scripts", "streamlit")
    else:  # Unix/Linux/macOS
        activate_script = os.path.join(".venv", "bin", "activate")
        streamlit_path = os.path.join(".venv", "bin", "streamlit")
    
    try:
        # 使用uv run直接运行，无需显式激活虚拟环境
        subprocess.run(["uv", "run", "streamlit", "run", "medical_agent.py"], check=True)
    except subprocess.CalledProcessError as e:
        print(f"❌ 启动应用失败: {e}")
        return False
    
    return True

def main():
    """主函数"""
    print("🚀 使用uv启动儿童肺炎治疗咨询专家智能体...")
    
    # 检查uv
    if not check_uv():
        return
    
    # 设置环境
    if not setup_env():
        return
    
    # 检查环境变量
    if not check_env():
        return
    
    # 启动应用
    activate_and_run()

if __name__ == "__main__":
    main()